<template>
    <div class="Photo-container">
    <img :src="img" alt="" class="update_photo" ref="image" />
    <div class="toolbar">
      <div class="cancel" @click="$emit('close')">取消</div>
      <div class="modify" @click="onConfirm">完成</div>
    </div>
  </div>
</template>

<script>
// 改变姓名
import Cropper from "cropperjs";
import "cropperjs/dist/cropper.css";
import { changePhotoAPI } from "@/api/api.config.js";
export default {
  name: "changePhoto",
  data() {
    return {
      cropper: null
    };
  },
  mounted() {
    const image = this.$refs.image;
    // cropper.js 第三方包的使用
    this.cropper = new Cropper(image, {
      viewMode: 1, // 如果为0 可以跑到外面去
      dragMode: "move", // 可否拖动
      aspectRatio: 16 / 9, // 裁剪比例
      autoCropArea: 1, // 裁剪区域大小
      cropBoxMovable: false, // 裁剪区域是否可以移动
      cropBoxResizable: false, // 裁剪区域 是否可以放大缩小
      background: false, // 要不要背景的网格
      movable: true,
      crop(event) {}
    });
    console.log(this.cropper);
  },
  props: {
    //   用户的头像
    img: {
      type: [String, Object],
      required: true
    }
  },
  methods: {
    async onConfirm() {
      this.cropper.getCroppedCanvas().toBlob((blob) => {
        this.loadPhotoChange(blob);
      })
    },
    async loadPhotoChange (blob) {
      this.$toast.loading({
        message: "加载中",
        duration: 0, // 表示没有加载好 不会停止
        forbidClick: true // 是否禁止背景点击
      });
      try {
        const formData = new FormData();
        formData.append("files", blob);
        let id = this.$store.state.userInfo._id
        const res = await changePhotoAPI(id, formData);
        console.log(res);
        // 更新视图数据
        this.$emit("upload-photo", res);

        // 关闭弹框
        this.$emit("close");

        // 提示成功
        this.$toast.success("请求成功");
      } catch (err) {
        this.$toast.fail("更新失败");
      }
    }
  }
};
</script>

<style scoped lang="less">
.Photo-container {
  background-color: #000;
  height: 100%;
  .update_photo {
    max-width: 100%;
  }
  .toolbar {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    display: flex;
    justify-content: space-between;
  }
  .cancel,
  .modify {
    width: 90px;
    height: 90px;
    font-size: 35px;
    display: flex;
    justify-content: center;
    align-items: center;
    color: #fff;
  }
}
</style>
